/*
 * @Descripttion: 
 * @version: 
 * @Author: 
 * @Date: 2022-04-25 11:40:02
 * @LastEditors: weidelong
 * @LastEditTime: 2022-05-07 15:09:12
 */
const express = require('express')
const jwt = require("../jwt/jwt")
const user = require('../db/userSchema_mobile')

/* 使用express中的Router对象 */
const router = express.Router()

// 获取当前时间  年-月-日 时:分:秒
function getCurrentTime() {
    let yy = new Date().getFullYear()
    let mm = new Date().getMonth() + 1
    let dd = new Date().getDate()
    let hh = new Date().getHours()
    let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes()
    let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds()
    let gettime = yy + '-' + mm + '-' + dd+' ' + hh + ':' + mf + ':' + ss
    return gettime
}

/* 移动端登陆接口 */
router.post('/loginmobiel', async (req, res) => {
	const { phone, password } = req.body
	let userObj = await user.findOne({phone})
	if (userObj) {
		// 有该用户，验证密码
		let passwordDb = userObj.password
		if (passwordDb == password) {
			// 密码正确,生成token
			let token = jwt.generateToken(userObj['id'], 60 * 60 * 24) // 24小时
			res.send({
				status: 200,
				data: {
					code: 0,
					token,
					userObj
				},
				msg: '登录成功'
			})
		} else {
			res.send({
				status: 404,
				msg: '密码错误'
			})
		}
	} else {
		res.send({
			status: 404,
			msg: '账号不存在'
		})
	}
})

/* 移动端注册接口 */
router.post('/registermobiel', async (req, res) => {
	const { phone, password } = req.body
	const defaultInfo = {
		userName: '用户' + Math.floor(Math.random() * 999999),
		sex: '男',
		userImg: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
        addTime: getCurrentTime(),
        flag: 1
	}
	const userInfo = {...req.body, ...defaultInfo}
	let userObj = await user.findOne({phone})
	if (userObj) {
		res.send({
			status: 404,
			msg: '该用户已注册，请直接登录'
		})
	} else {
		user.create(userInfo, (err, result) => {
			if (err) {
				throw error
			} else {
				res.send({
					status: 200,
					data: {
						code: 0,
					},
					msg: '注册成功'
				})
			}
		})
	}
})

// 获取用户信息
router.get('/selectUserInfo', async (req, res) => {
	const { phone } = req.query
	let userInfo = await user.find({phone})
	if (userInfo) {
		const obj = {
			id: userInfo.id,
			phone: userInfo.phone,
			name: userInfo.userName
		}
		res.send({
			status: 200,
			data: {
				code: 0,
				userInfo: obj
			},
			msg: '查询成功'
		})
	} else {
		res.send({
			status: 500,
			msg: '查询失败'
		})
	}
})

/* 导出router对象 */
module.exports = router